package com.antoco.operation.bigscreen.controller.modelcontroller.impl;

import com.antoco.operation.bigscreen.controller.modelcontroller.intf.TjInsController;
import com.antoco.operation.bigscreen.model.dto.TjInsDTO;
import com.antoco.operation.bigscreen.model.entity.TjIns;
import com.antoco.operation.bigscreen.mapper.TjInsMapper;
import com.antoco.operation.bigscreen.service.autogeneration.intf.TjInsService;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

@RequestMapping("/model/tj-ins")
@RestController
public class TjInsControllerImpl implements TjInsController {
    private final TjInsService tjInsService;
    private final TjInsMapper tjInsMapper;

    public TjInsControllerImpl(TjInsService tjInsService, TjInsMapper tjInsMapper) {
        this.tjInsService = tjInsService;
        this.tjInsMapper = tjInsMapper;
    }

    @Override
    @PostMapping
    @ResponseStatus(HttpStatus.CREATED)
    public TjInsDTO save(@RequestBody TjInsDTO tjInsDTO) {
        TjIns tjIns = tjInsMapper.asEntity(tjInsDTO);
        return tjInsMapper.asDTO(tjInsService.save(tjIns));
    }

    @Override
    @GetMapping("/{id}")
    public TjInsDTO findById(@PathVariable("id") String id) {
        TjIns tjIns = tjInsService.findById(id).orElse(null);
        return tjInsMapper.asDTO(tjIns);
    }

    @Override
    @DeleteMapping("/{id}")
    public void delete(@PathVariable("id") String id) {
        tjInsService.deleteById(id);
    }

    @Override
    @GetMapping
    public List<TjInsDTO> list() {
        return tjInsMapper.asDTOList(tjInsService.findAll());
    }

    @Override
    @GetMapping("/page-query")
    public Page<TjInsDTO> pageQuery(Pageable pageable) {
        Page<TjIns> tjInsPage = tjInsService.findAll(pageable);
        List<TjInsDTO> dtoList = tjInsPage
                .stream()
                .map(tjInsMapper::asDTO).collect(Collectors.toList());
        return new PageImpl<>(dtoList, pageable, tjInsPage.getTotalElements());
    }

    @Override
    @PutMapping("/{id}")
    public TjInsDTO update(@RequestBody TjInsDTO tjInsDTO, @PathVariable("id") String id) {
        TjIns tjIns = tjInsMapper.asEntity(tjInsDTO);
        return tjInsMapper.asDTO(tjInsService.update(tjIns, id));
    }
}